import React, {Component, useState} from 'react';
import {EditableProTable, nanoid, PageContainer, ProColumns, ProFormUploadButton} from "@ant-design/pro-components";
import {Button, Col, Form, message, Modal, Row, Space, Typography} from "antd";
import {Card, Upload} from "antd";
import ProForm from "@ant-design/pro-form";
import {
  DownloadApi,
  FillApi,
  GetUploadedFiles, NoDataAPI,
  SchoolPass, SchoolReject,
  UploadApi,
  UploadWordPath
} from "@/services/School/SchoolApi";
import {ServerMessages} from "@/services/ServerMessages";
import {history} from "umi";
import {DownloadOutlined, ExclamationCircleOutlined, UploadOutlined} from "@ant-design/icons";
import {DownloadByNameApi} from "@/services/Province/ProvinceApi";
import {ShowError} from "@/utils/format";

type DataSourceType = {
  key: string;
  project_type?: string;
  project_person?: string;
  project_year?: string;
};

//上传
const upload = UploadApi('/api/index/cultivate-talents/education/political-edu-template',
  (info) => {
    console.log("@success", info)
    if (info.file.response.status === 0) {
      message.success(info.file.response.message)
      history.push('/cultivate-talents/education')
    } else {
      ShowError(info.file.response.message)
    }
  })

const defaultData: DataSourceType[] = [
  {
    key: nanoid(),
    project_type: '',
    project_person: '',
    project_year: '',
  },
  {
    key: nanoid(),
    project_type: '',
    project_person: '',
    project_year: '',
  },
  {
    key: nanoid(),
    project_type: '',
    project_person: '',
    project_year: '',
  }
]

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '荣誉表彰/项目类型',
    dataIndex: 'project_type',
    formItemProps: () => {
      return {
        rules: [{required: true, message: '此项为必填项'}]
      };
    },
  },
  {
    title: '获得者',
    dataIndex: 'project_person',
    formItemProps: () => {
      return {
        rules: [{required: true, message: '此项为必填项'}]
      };
    },
  },
  {
    title: '获得年份',
    dataIndex: 'project_year',
    formItemProps: () => {
      return {
        rules: [{required: true, message: '此项为必填项'}]
      };
    },
  },
  {
    title: '操作',
    valueType: 'option',
  },
]

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.key),
  );
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm()
  const status_is_show = (history.location.query.flag === 'display') || (history.location.query.id && history.location.query.fill_id)
  const status_is_check = history.location.query.flag === 'check'
  const is_seen = history.location.query.is_seen

  const handleCheck = () => {
    SchoolPass(history.location.query.id).then(response => {
      console.log(response)
      if (response.status === 0) {
        message.success(response.message)
        history.goBack()
      } else {
        ShowError(response.message)
      }
    })
    // history.goBack()
  }

  const { confirm } = Modal;


  const showConfirm = () => {
    confirm({
      title: '您确认驳回吗?',
      icon: <ExclamationCircleOutlined />,
      content: '驳回后，学科用户可重新填报。',
      onOk() {
        SchoolReject(history.location.query.id).then(response => {
          if (response.status === 0) {
            message.success(response.message)
            history.goBack()
          } else {
            ShowError(response.message)
          }
        }, () => {
          ShowError(ServerMessages.error_message)
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };


  const handleBack = () => {
    showConfirm()
    // SchoolReject(history.location.query.fill_id).then(response => {
    //   if (response.status === 0) {
    //
    //   } else {
    //     ShowError(response.message)
    //   }
    // })
  }


  const path = []
  let loading = true
  const download = '2_1_1docx'

  const [downloadList, setDownloadList] = useState([]);


  return (
    <Space direction="vertical" size="middle" style={{display: 'flex'}}>
      <PageContainer
        title="思想政治教育特色与成效"
        content={<Typography.Text
          type="danger">2021年1月1日至今，学科思想政治教育特色做法和主要成效，如“三全育人”综合改革情况等，要求突出课程思政改革、社会实践开展、意识形态阵地管理、基层党组织建设、思政队伍建设等方面的特色做法和主要成效。<br/>仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。</Typography.Text>}>
        <Card bordered={false}>
          <ProForm
            request={() => {
              return new Promise(resolve => {
                if (status_is_check) {
                  GetUploadedFiles('/api/index/school-query/review-download-query-wordname', history.location.query.id).then(response => {
                    if (response.status === 0) {
                      console.log(response.filenameList)
                      setDownloadList(response.filenameList)
                    }
                  })
                } else if (status_is_show) {
                  GetUploadedFiles('/api/wordname-query-download', download).then(response => {
                    if (response.status === 0) {
                      console.log(response.filenameList)
                      setDownloadList(response.filenameList)
                    }
                  })
                }
                resolve(true)
              })
            }}
            onFinish={() => {
              return new Promise(resolve => {

                if (loading) {
                  resolve(true)
                } else {
                  console.log("@@path", path)
                  UploadWordPath('/api/index/cultivate-talents/education/political-edu-word', path).then(response => {
                    console.log("@返回数据", response)
                    if (response.status === 0) {
                      message.success(response.message)
                      history.goBack()
                      resolve(true)
                    } else {
                      ShowError(response.message)
                      history.goBack()
                      resolve(true)
                    }
                  }, () => {
                    ShowError(ServerMessages.error_message)
                    resolve(true)
                  })
                }
              })
            }}
            hideRequiredMark
            style={{margin: 'auto', marginTop: 8}}
            name="basic"
            layout="horizontal"
            labelCol={{span: 8}}
            submitter={{
              render: (props, doms) => {
                if (status_is_check && is_seen === '0') {
                  return <Row>
                    <Col offset={8}>
                      <Space>
                        <Button onClick={() => { history.goBack() }}>返回</Button>
                        <Button onClick={handleCheck} type="primary">通过</Button>
                        <Button danger onClick={handleBack}>驳回</Button>
                        <Button disabled>已提交</Button>
                      </Space>
                    </Col>
                  </Row>
                } else if (status_is_check && is_seen === '1') {
                  return <Row>
                    <Col offset={8}>
                      <Space>
                        <Button onClick={() => { history.goBack() }}>返回</Button>
                        <Button disabled>已审核</Button>
                      </Space>
                    </Col>
                  </Row>
                } else if (status_is_show) {
                  return (
                    <Row>
                      <Col offset={8}>
                        <Button onClick={() => { history.goBack() }}>返回</Button>
                        <Button disabled>已提交</Button>
                      </Col>
                    </Row>
                  )
                }
                return (
                  <Row>
                    <Col offset={8}>
                      <Space>
                        <Button onClick={() => { history.goBack() }}>返回</Button>
                        <Button onClick={() => {
                          NoDataAPI(download).then(res => {
                            if (res.status === 0) {
                              message.success(res.message)
                              history.goBack()
                            } else {
                              ShowError("提交失败，请稍后重试.")
                            }
                          }, () => {
                            ShowError(ServerMessages.error_message)
                          })
                        }
                        } type="default">无相关数据</Button>

                        <Button onClick={() => {
                          window.location.reload()
                        }}>重置</Button> {doms}</Space>
                    </Col>
                  </Row>
                );
              },
              resetButtonProps: {
                style: {
                  // 隐藏重置按钮
                  display: 'none',
                },
              },
              submitButtonProps: {
                style: {
                  marginLeft: '-8px'
                }
              },
            }}>
            {!status_is_show && (
            <Form.Item label="请上传相关文档">
              <Upload {...UploadApi('/api/index/cultivate-talents/education/political-edu-word-template', (response) => {
                try {
                  path.push(response.file.response.data[0].path)
                  console.log(path.length, response.fileList.length, path.length === response.fileList.length)
                  if (path.length === response.fileList.length) {
                    console.log("@loading false!")
                    loading = false
                  }
                  if (path.length === 0) {
                    loading = true
                  }
                } catch {
                  ShowError('上传失败')
                }
              })}>
                <Button type="default" icon={<UploadOutlined/>}>上传文档</Button>
              </Upload>
            </Form.Item>
            )}
            {status_is_show && (
              <Space>
                {downloadList.map((item, idx) => {
                  return <Button onClick={() => {
                    DownloadByNameApi(item)
                  }
                  } key={item}>下载文件{idx+1}</Button>
                })}
              </Space>
            )}
          </ProForm>
        </Card>
      </PageContainer>
</Space>
)
  ;
}
